from datetime import datetime

from django_redis import get_redis_connection
from rest_framework import status, mixins
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import ObtainJSONWebToken

from goods.models import SKU
from goods.serializers import SKUSerializer
from users import serializers, constants
from .serializers import CreateUserSerializer, UserBrowseHistorySerializer
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import User
from carts.utils import merge_cart_cookie_to_redis


# Create your views here.


class UserView(CreateAPIView):
    """注册"""

    # 指定序列化器
    serializer_class = CreateUserSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        response = Response(serializer.data, status=status.HTTP_201_CREATED)
        merge_cart_cookie_to_redis(request, user, response)
        return response


class UsernameCountView(APIView):
    """判断用户是否已经存在"""

    def get(self, requset, username):
        # 用username去User模型中查询次用户名的数据
        count = User.objects.filter(username=username).count()
        data = {
            'username': username,
            'count': count
        }
        # 响应
        return Response(data)


class MobileCountView(APIView):
    """判断手机号码是否已经存在"""

    def get(self, request, mobile):
        # 用username去User模型中查询此用户名的数据
        count = User.objects.filter(mobile=mobile).count()
        data = {
            'mobile': mobile,
            'count': count
        }
        # 响应
        return Response(data)


# GET url(r'^user/$', views.UserDetailView.as_view()),
class UserDetailView(RetrieveAPIView):
    """
    展示用户详情
    """
    serializer_class = serializers.UserDetailSerializer  # 指定序列化器类
    permission_classes = [IsAuthenticated]  # 指定视图的权限,只有登陆的用户能查询到数据
    '''
    instance = self.get_object()  # Retrieve 扩展中此行代码由于路由中没有PK所以此方法获取不到查询集中的单个模型对象
    '''

    def get_object(self):
        """重写获取单一模型对象的方法,手动从请求对象获取user,并返回"""
        return self.request.user


# PUT  url(r'^emails/$', views.EmailView.as_view()),
class EmailView(UpdateAPIView):
    """
    保存用户邮箱
    """
    serializer_class = serializers.EmailSerializer  # 指定序列化器类
    permission_classes = [IsAuthenticated]  # 指定视图的权限

    def get_object(self, *args, **kwargs):
        return self.request.user


# url(r'^emails/verification/$', views.VerifyEmailView.as_view()),
class VerifyEmailView(APIView):
    """
    邮箱验证,激活邮箱
    # 1.获取前端传入的查询参数
    # 2.对获取到的token进行解密,并查询user
    # 3.判断token是否有效
    # 4.修改user对象的email_active字段为True
    # 5.响应
    """

    def get(self, request):
        # 获取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证token
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializers.UserAddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


# /browse_histories/
class UserBrowseHistoryView(CreateAPIView):
    """保存用户浏览记录"""
    # 指定用户权限, 验证是否登录
    permission_classes = [IsAuthenticated]

    # 指定序列化器
    serializer_class = UserBrowseHistorySerializer

    def get(self, request):
        """获取用户浏览记录"""
        # 1.创建redis连接对象
        redis_conn = get_redis_connection('history')
        # 2.获取当前的请求用户
        user = request.user
        # 调用lrange() 获取当前用户的浏览记录
        sku_id_list_bytes = redis_conn.lrange('history_%s' % user.id, 0, -1)
        # 通过sku_id取出一个一个的sku模型
        # SKU.objects.filter(id__in=sku_id_list_bytes)
        sku_list = []  # 为了保存浏览商品的顺序只能自己遍历一个一个查和添加到列表
        for sku_id_bytes in sku_id_list_bytes:
            sku = SKU.objects.get(id=sku_id_bytes)
            sku_list.append(sku)
        # 把模型进行序列化  创建序列化器时 instance 参数可以传递 模型对象, 字典  (查询集/列表   many=True)
        serializer = SKUSerializer(sku_list, many=True)

        # 响应
        return Response(serializer.data)


jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER


class UserAuthorizeView(ObtainJSONWebToken):
    """自定义jwt登录视图"""

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            # 账号密码登录合并购物车
            merge_cart_cookie_to_redis(request, user, response)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
